/*
 * BanBu_BlacklistViewController
 * @description 本文件提供黑名单列表界面的ViewController
 * @package
 * @author 		***
 * @copyright
 * @version 		1.0
 * @description 本文件提供黑名单列表界面的ViewController
 */

#import "BanBu_BlacklistViewController.h"
#import "BanBu_ListCell.h"
#import "AppDataManager.h"
#import "AppCommunicationManager.h"
#import "TKLoadingView.h"
#import "UIImageView+WebCache.h"
#import "BanBu_NavButton.h"
#import "BanBu_ImageView.h"
@interface BanBu_BlacklistViewController ()

@end

@implementation BanBu_BlacklistViewController

@synthesize dataArr = _dataArr;

- (id)init
{
    self = [super initWithStyle:UITableViewStylePlain];
    if (self) {
        // Custom initialization
    }
    return self;
}
-(void)popself
{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    self.tableView.backgroundView = nil;
    self.tableView.backgroundColor = [UIColor colorWithRed:255.0/255 green:250.0/255 blue:240.0/255 alpha:1.0];    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.title = NSLocalizedString(@"blackTitle", nil);
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    
    [self setRefreshing];
    alreadyRefresh = YES;
    isLoading      = NO;
    self.tableView.frame = CGRectMake(0, 25, __MainScreen_Width, 50);
    //    summary = [[NSDictionary alloc]init];
    moreView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 40)];
    lab = [[UILabel alloc] initWithFrame:CGRectMake(0, 10, 320,20)];
    lab.font= [UIFont systemFontOfSize:15];
    lab.backgroundColor =[UIColor colorWithRed:254.0/255.0 green:250.0/255.0 blue:239.0/255.0 alpha:1];
    lab.textAlignment = kTextAlignmentCenter;
    lab.textColor = [UIColor grayColor];
    lab.backgroundColor = [UIColor clearColor];
    [moreView addSubview:lab];
    
    loadingView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    loadingView.hidden = NO;
    [loadingView setHidesWhenStopped:YES];
    loadingView.frame = CGRectMake(0, 0, 50, 50);
    loadingView.center = CGPointMake(160-([NSLocalizedString(@"loadingNotice", nil) sizeWithFont:[UIFont systemFontOfSize:15] constrainedToSize:CGSizeMake(320, 20) lineBreakMode:kTextLineBreakByWordWrapping].width/2)-15, 20);
    moreView.backgroundColor = [UIColor clearColor];
    [moreView addSubview:loadingView];
    [loadingView release];
    
    cacheArray = [[NSMutableArray alloc] initWithCapacity:20];
    
    
    BanBu_ImageView *img = [[[BanBu_ImageView alloc] initWithBackGroundImageType:UIImageViewCreatTypeTable] autorelease];
    self.tableView.backgroundView = img;
    

    
    
    
    
    CGFloat btnLen = [NSLocalizedString(@"unlockButton", nil) sizeWithFont:[UIFont systemFontOfSize:14] constrainedToSize:CGSizeMake(150, 30)].width;
    unlock = [[BanBu_NavButton alloc] initWithButtonType:UIButtonCreatTypeNormal];
    unlock.position = ButtonPositionRight;
    unlock.frame=CGRectMake(0, 0, btnLen+20, 30);
    [unlock addTarget:self action:@selector(unlock:) forControlEvents:UIControlEventTouchUpInside];
    //    [unlock setTitleEdgeInsets:UIEdgeInsetsMake(3, 2, 2, 2)];
    [unlock setTitle:NSLocalizedString(@"unlockButton", nil) forState:UIControlStateNormal];
    unlock.titleLabel.font = [UIFont systemFontOfSize:14];
    UIBarButtonItem *unlockItem = [[[UIBarButtonItem alloc] initWithCustomView:unlock] autorelease];
    self.navigationItem.rightBarButtonItem = unlockItem;
    [unlock release];
    
    _dataArr = [[NSMutableArray alloc] init];
    
    [self.tableView addObserver:self forKeyPath:@"contentOffset" options:NSKeyValueObservingOptionNew context:self.tableView];
}

- (void)unlock:(UIButton *)button
{
    if(_dataArr.count){
        [self.tableView setEditing:!self.tableView.editing animated:YES];
        [button setTitle:self.tableView.editing?NSLocalizedString(@"finishButton", nil):NSLocalizedString(@"unlockButton", nil) forState:UIControlStateNormal];
    }
    
    
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    //    self.dataArr = nil;
}

- (void)dealloc
{
    //    [_dataArr release];
    [AppComManager cancalHandlesForObject:self];
    [self.tableView removeObserver:self forKeyPath:@"contentOffset"];
    [super dealloc];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    if(!_dataArr.count){
        [self setRefreshing];
    }
}

-(void)viewWillDisappear:(BOOL)animated
{
    
    [super viewWillAppear:animated];
    [AppComManager cancalHandlesForObject:self];
    
    
}
-(void)rotateImageView
{
    UIImageView *la=(UIImageView *)[self.navigationController.view viewWithTag:100];
    
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.3];
    CGAffineTransform transform = CGAffineTransformRotate(la.transform, -M_PI);
    la.transform = transform;
    [UIView commitAnimations];
}
-(void)loadingData{
    if(_isLoadingRefresh)
        _currentPage = 1;
    else if(_currentPage ==1)
    {
        _currentPage = 3;
    }
    else
        _currentPage ++;
    
    NSMutableDictionary *parDic = [NSMutableDictionary dictionary];
    [parDic setValue:[MyAppDataManager getLanguageSubmitToServer] forKey:@"lang"];
    [parDic setValue:[NSString stringWithFormat:@"%i",_currentPage] forKey:PageNo];
    [parDic setValue:@"x" forKey:@"linkkind"];
    [AppComManager getBanBuData:BanBu_Get_Friend_OfMy par:parDic delegate:self];
    
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [_dataArr count];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 84;
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *ListCellIdentifier = @"ListCellIdentifier";
    BanBu_ListCell *cell = (BanBu_ListCell *)[tableView dequeueReusableCellWithIdentifier:ListCellIdentifier];
    if(cell == nil)
    {
        cell = [[[BanBu_ListCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ListCellIdentifier] autorelease];
        cell.selectionStyle = UITableViewCellSelectionStyleBlue;
        
    }
    
    NSDictionary *aData = [_dataArr objectAtIndex:indexPath.row];
    
    [cell updateListCell:aData];
    return cell;
}


- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

- (BOOL)tableView:(UITableView *)tableView shouldIndentWhileEditingRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath{
    return NSLocalizedString(@"unlockButton", nil);
}
-(UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewCellEditingStyleDelete;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        
        NSMutableDictionary *parDic = [NSMutableDictionary dictionary];
        [parDic setValue:[[_dataArr objectAtIndex:indexPath.row] valueForKey:@"userid"] forKey:LinkTouID];
        [parDic setValue:@"unlink" forKey:Action];
        [AppComManager getBanBuData:BanBu_Set_Friend_Link par:parDic delegate:self];
        
        
        
        [_dataArr removeObjectAtIndex:indexPath.row];
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationTop];
        [self.tableView setEditing:!self.tableView.editing animated:YES];
        [unlock setTitle:self.tableView.editing?NSLocalizedString(@"finishButton", nil):NSLocalizedString(@"unlockButton", nil) forState:UIControlStateNormal];
        
    }
    
}


#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
}

#pragma mark - BanBuDelegate

- (void)banbuRequestDidFinished:(NSDictionary *)resDic error:(NSError *)error{
    
    self.navigationController.view.userInteractionEnabled = YES;
    [TKLoadingView dismissTkFromView:self.view animated:YES afterShow:0.0];
    if(error)
    {
        numberOfblack = 0;
        [TKLoadingView showTkloadingAddedTo:self.view title:NSLocalizedString(@"network_error", nil) activityAnimated:NO duration:2.0];
//        if([error.domain isEqualToString:BanBuDataformatError])
//        {
//            [TKLoadingView showTkloadingAddedTo:self.view title:NSLocalizedString(@"network_error", nil) activityAnimated:NO duration:2.0];
//        }
//        else
//        {
//            [TKLoadingView showTkloadingAddedTo:self.view title:NSLocalizedString(@"network_error", nil) activityAnimated:NO duration:2.0];
//        }
        
        [self finishedLoading];
        [loadingView stopAnimating];
        if(_currentPage>3)
        {
            _currentPage--;
        }
        else
        {
            _currentPage =1;
        }
        return;
    }
    if([AppComManager respondsDic:resDic isFunctionData:BanBu_Get_Friend_OfMy]){
        if([[resDic valueForKey:@"ok"]boolValue]){
            if(_isLoadingRefresh)
            {
                [_dataArr removeAllObjects];
                [cacheArray removeAllObjects];
                NSString *black = [[resDic valueForKey:@"friendlist"] valueForKey:@"x"];
                if(black.length)
                {
                    numberOfblack = [[black componentsSeparatedByString:@","] count];
                }
                else
                {
                    numberOfblack  = 0;
                }
                if([[resDic valueForKey:@"list"]count])
                {
                    self.tableView.tableFooterView = moreView;
                }

                if([[resDic valueForKey:@"list"] count]>20)
                {
                    [_dataArr addObjectsFromArray:[[resDic valueForKey:@"list"] subarrayWithRange:NSMakeRange(0, 20)]];
                    [cacheArray addObjectsFromArray:[[resDic valueForKey:@"list"] subarrayWithRange:NSMakeRange(20, [[resDic valueForKey:@"list"] count]-20)]];
                }
                else
                {
                    [_dataArr addObjectsFromArray:[resDic valueForKey:@"list"]];
                }
            }
            else
            {
                //对名字和话，进行替换后，在存储
                [cacheArray addObjectsFromArray:[resDic valueForKey:@"list"]];
                if(!alreadyRefresh&&isLoading&&cacheArray.count)
                {
                    [self startLoadNextPage];
                    [self loadingData];
                }
                if(!cacheArray.count)
                {
                    if(_currentPage>3)
                    {
                        _currentPage--;
                    }
                    else
                    {
                        _currentPage =1;
                    }
                    [loadingView stopAnimating];
                    alreadyRefresh = YES;
                    lab.text = NSLocalizedString(@"noData", nil);
                }
            }
            
            
        }else{
            
            if(_currentPage>3)
            {
                _currentPage--;
            }
            else
            {
                _currentPage =1;
            }
            numberOfblack = 0;
            if([[resDic valueForKey:@"error"] isEqualToString:@"__loginidinvalid__"]){
                [self.navigationController popToRootViewControllerAnimated:NO];
                
            }
            [TKLoadingView showTkloadingAddedTo:self.view title:[MyAppDataManager IsInternationalLanguage:[resDic valueForKey:@"error"]] activityAnimated:NO duration:1.0];
        }
        
    }
    if([AppComManager respondsDic:resDic isFunctionData:BanBu_Set_Friend_Link]){
        NSString *black = [[resDic valueForKey:@"friendlist"] valueForKey:@"x"];
        if(black.length)
        {
            numberOfblack = [[black componentsSeparatedByString:@","] count];
        }
        else
        {
            numberOfblack  = 0;
        }
        if([[resDic valueForKey:@"list"]count])
        {
            self.tableView.tableFooterView = moreView;
        }
        

        NSMutableDictionary *uidDic = [NSMutableDictionary dictionaryWithDictionary:[UserDefaults valueForKey:MyAppDataManager.useruid]];
        [uidDic setValue:[resDic valueForKey:@"friendlist"] forKey:FriendShip];
        [uidDic setValue:[resDic valueForKey:@"friendsum"] forKey:@"friendsum"];
        [UserDefaults setValue:uidDic forKey:MyAppDataManager.useruid];
        [UserDefaults synchronize];
        if(![[resDic valueForKey:@"ok"]boolValue]){
            if([[resDic valueForKey:@"error"] isEqualToString:@"__loginidinvalid__"]){
                [self.navigationController popToRootViewControllerAnimated:NO];
                
            }
        }
    }
    
    [self.tableView reloadData];
    isLoading = NO;
    [self finishedLoading];
    
    
    
}



-(void)startLoadNextPage
{
    if(cacheArray.count)
    {
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:[_dataArr count]+1 inSection:0];
        
        [_dataArr addObjectsFromArray:cacheArray];
        [cacheArray removeAllObjects];
            [UIView animateWithDuration:0.5 animations:^{
            [self.tableView reloadData];
            [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
        }];
        alreadyRefresh = YES;
        [loadingView stopAnimating];
    }
    if(!cacheArray.count)
    {
        [self loadingData];
        isLoading = YES;
    }
}
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    if([keyPath isEqual:@"contentOffset"])
    {
        if(self.tableView.contentOffset.y>self.tableView.contentSize.height-__MainScreen_Height+44&&alreadyRefresh)
        {
            if(!isLoading&&!_isLoadingRefresh&&_dataArr.count<numberOfblack)
            {
                alreadyRefresh = NO;
                _isLoadingRefresh = NO;
                [loadingView startAnimating];
                lab.text = NSLocalizedString(@"loadingNotice", nil);
                self.tableView.tableFooterView = moreView;
                isLoading = YES;
                [self performSelector:@selector(startLoadNextPage) withObject:nil afterDelay:0.5];
            }
        }
        
    }
}


@end
